package com.ruoyi.web.controller.assets;


import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.BorrowLog;
import com.ruoyi.system.service.IBrAuditService;
import com.ruoyi.system.service.IOliveAssetsBorrowService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.OliveAssets;
import com.ruoyi.system.service.IOliveAssetsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产借还Controller
 *
 * @author hzl
 * @date 2025-01-26
 */
@RestController
@RequestMapping("/assets/borrow")
public class OliveAssetsBorrowController extends BaseController
{
    @Autowired
    private IOliveAssetsBorrowService oliveAssetsBorrowService;
    @Autowired
    private IBrAuditService brAuditService;

    /**
     * 查询资产借还列表
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:list')")
    @GetMapping("/list")
    public TableDataInfo list(OliveAssets oliveAssets)
    {
        startPage();
        List<OliveAssets> list = oliveAssetsBorrowService.selectOliveAssetsList(oliveAssets);
        return getDataTable(list);
    }

    /**
     * 导出资产借还列表
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:export')")
    @Log(title = "资产借还", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OliveAssets oliveAssets)
    {
        List<OliveAssets> list = oliveAssetsBorrowService.selectOliveAssetsList(oliveAssets);
        ExcelUtil<OliveAssets> util = new ExcelUtil<OliveAssets>(OliveAssets.class);
        util.exportExcel(response, list, "资产借还数据");
    }

    /**
     * 获取资产借还详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:query')")
    @GetMapping(value = "/{assetId}")
    public AjaxResult getInfo(@PathVariable("assetId") String assetId)
    {
        return success(oliveAssetsBorrowService.selectOliveAssetsByAssetId(assetId));
    }

    /**
     * 新增资产借还
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:add')")
    @Log(title = "资产借还", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OliveAssets oliveAssets)
    {
        return toAjax(oliveAssetsBorrowService.insertOliveAssets(oliveAssets));
    }

    /**
     * 修改资产借还
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:edit')")
    @Log(title = "资产借还", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OliveAssets oliveAssets)
    {
        return toAjax(oliveAssetsBorrowService.updateOliveAssets(oliveAssets));
    }

    /**
     * 删除资产借还
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:remove')")
    @Log(title = "资产借还", businessType = BusinessType.DELETE)
    @DeleteMapping("/{assetIds}")
    public AjaxResult remove(@PathVariable String[] assetIds)
    {
        return toAjax(oliveAssetsBorrowService.deleteOliveAssetsByAssetIds(assetIds));
    }

    /**
     * 借用资产
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:request')")
    @Log(title = "资产借还", businessType = BusinessType.OTHER)
    @PostMapping("/request")
    public AjaxResult requestBorrow(@RequestBody OliveAssets oliveAssets) {
        // 获取当前登录用户的ID
        Long borrowerId = Long.valueOf(getUserId());

        // 获取借用资产的ID
        String assetId = oliveAssets.getAssetId();
        // 创建一个BorrowLog对象
        BorrowLog borrowLog = new BorrowLog();
        // 设置借用人的ID
        borrowLog.setUserId(borrowerId);
        // 设置借用资产的ID
        borrowLog.setAssetId(assetId);
        // 设置设备状态为“待审核”
        oliveAssets.setAssetStatus(5L);
        // 设置默认审核状态为0
        borrowLog.setAuditStatus(0);
        // 设置当前时间为借用时间
        borrowLog.setBorrowTime(new Date());
        // 设置借用位置
        borrowLog.setBorrowLocation("["+ oliveAssets.getAssetLatitude() + "," + oliveAssets.getAssetLongitude() + "]");
        // 插入借用日志
        brAuditService.insertBorrowLog(borrowLog);
        return toAjax(oliveAssetsBorrowService.updateOliveAssets(oliveAssets));
    }

    /**
     * 归还资产
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:return')")
    @Log(title = "资产借还", businessType = BusinessType.OTHER)
    @PostMapping("/return")
    public AjaxResult returnAsset(@RequestBody OliveAssets oliveAssets) {
        // 设置设备状态为“空闲”
        oliveAssets.setAssetStatus(0L);
        // 获取资产ID
        String assetId = oliveAssets.getAssetId();
        if (assetId == null || assetId.isEmpty()) {
            return AjaxResult.error("资产ID不能为空");
        }
        // 根据资产ID获取借用日志
        BorrowLog borrowLog = brAuditService.getBorrowLogByAssetId(assetId);

        if (borrowLog == null) {
            return AjaxResult.error("未找到对应的借用记录");
        }
        // 设置当前时间为归还时间
        borrowLog.setReturnTime(new Date());
        // 设置归还位置
        borrowLog.setReturnLocation("["+ oliveAssets.getAssetLatitude() + "," + oliveAssets.getAssetLongitude() + "]");
        // 更新借用日志
        brAuditService.updateBorrowLog(borrowLog);
        return toAjax(oliveAssetsBorrowService.updateOliveAssets(oliveAssets));
    }

    /**
     * 审核借用请求
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:approve')")
    @Log(title = "资产借还", businessType = BusinessType.UPDATE)
    @PostMapping("/approve/{assetId}")
    public AjaxResult approveBorrow(@RequestBody BorrowLog borrowLog) {

        String assetId = borrowLog.getAssetId();
        // 验证assetId是否为空
        if (assetId == null || assetId.isEmpty()) {
            return AjaxResult.error("资产ID不能为空");
        }
        System.out.println("assetId: " + assetId);
        OliveAssets asset = new OliveAssets();
        // 设置设备状态为“使用中”
        asset.setAssetId(assetId);
        asset.setAssetStatus(1L);
        // 更新资产状态
        int updateResult = oliveAssetsBorrowService.updateOliveAssets(asset);
        if (updateResult > 0) {
            // 更新审核状态
            borrowLog.setAuditStatus(1); // 假设1表示审核通过
            // 更新审核结果
            borrowLog.setAuditResult(1);
            borrowLog.setBorrowTime(new Date()); // 更新审核时间
            borrowLog.setApproveTime(new Date());
            borrowLog.setAdminId(String.valueOf(getUserId()));

            brAuditService.updateBorrowLog(borrowLog);
            return AjaxResult.success("审核通过");
        } else {
            return AjaxResult.error("更新资产状态失败");
        }

    }

    /**
     * 拒绝借用请求
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:reject')")
    @Log(title = "资产借还", businessType = BusinessType.UPDATE)
    @PostMapping("/reject/{assetId}")
    public AjaxResult rejectBorrow(@RequestBody BorrowLog borrowLog) {

        String assetId = borrowLog.getAssetId();
        // 验证assetId是否为空
        if (assetId == null || assetId.isEmpty()) {
            return AjaxResult.error("资产ID不能为空");
        }
        System.out.println("assetId: " + assetId);
        OliveAssets asset = new OliveAssets();
        // 设置设备状态为“使用中”
        asset.setAssetId(assetId);
        asset.setAssetStatus(0L);
        // 更新资产状态
        int updateResult = oliveAssetsBorrowService.updateOliveAssets(asset);
        if (updateResult > 0) {
            // 更新审核状态
            borrowLog.setAuditStatus(1); // 1表示已审核
            // 更新审核结果
            borrowLog.setAuditResult(0);
            borrowLog.setBorrowTime(new Date()); // 更新审核时间
            borrowLog.setApproveTime(new Date());
            borrowLog.setAdminId(String.valueOf(getUserId()));

            brAuditService.updateBorrowLog(borrowLog);
            return AjaxResult.success("审核未通过");
        } else {
            return AjaxResult.error("更新资产状态失败");
        }
    }

}
